package com.hotel.tv.runtime.security;

import com.autumn.runtime.session.AutumnUser;
import com.autumn.runtime.session.AutumnUserDeviceInfo;
import com.autumn.runtime.session.DefaultAutumnUserDeviceInfo;
import com.autumn.security.crypto.DefaultAutumnDeviceProvider;
import com.autumn.security.token.CredentialsDeviceInfo;
import com.autumn.spring.boot.properties.AutumnAuthProperties;
import com.autumn.util.AutoMapUtils;
import com.autumn.util.StringUtils;
import com.autumn.util.security.HashUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.UUID;

/**
 * 设备自定义匹配器
 * <p>
 * </p>
 *
 * @description TODO
 * @author: 老码农
 * @create: 2020-04-21 15:19
 **/
@Component
@Primary
public class HotelDeviceProvider extends DefaultAutumnDeviceProvider {

    /**
     * @param authProperties
     */
    public HotelDeviceProvider(AutumnAuthProperties authProperties) {
        super(authProperties);
    }

    @Override
    public AutumnUserDeviceInfo createStorage(AutumnUser user, CredentialsDeviceInfo rawCredentialsDeviceInfo) {
        DefaultAutumnUserDeviceInfo userDeviceInfo = AutoMapUtils.map(rawCredentialsDeviceInfo, DefaultAutumnUserDeviceInfo.class);
        String token = (UUID.randomUUID().toString().replace("-", "") + "."
                + StringUtils.getLeft(UUID.randomUUID().toString().replace("-", ""), 16)
                + "."
                + StringUtils.getRigth(UUID.randomUUID().toString().replace("-", ""), 16)
        ).toUpperCase(Locale.ENGLISH);

        userDeviceInfo.setDeviceToken(token);

        //对设备id进行加密
        String source = String.format("%s_%s_%s", user.getId(), rawCredentialsDeviceInfo.getDeviceIdentification(),
                StringUtils.reverseOrder(rawCredentialsDeviceInfo.getDeviceIdentification()));
        userDeviceInfo.setDeviceIdentification(HashUtils.md5(source, this.getCharset()));

        userDeviceInfo.setExpires(this.getAuthProperties().getDeviceExpire());

        return userDeviceInfo;
    }
}
